package com.netty8018.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author liyanhao
 * @Date 2023-02-04 21:16
 */
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        //客户端需要一个时间虚幻组
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            //创建客户端对象
            //注意客户端使用的不是 ServerBootstrap 而是Bootstrap
            Bootstrap bootstrap = new Bootstrap();
            //设置相关参数
            bootstrap.group(group)//设置线程租
                    .channel(NioSocketChannel.class)//设置为客户端通道的实现类 反射
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyClientHeandler());//加入客户端自己的处理器
                        }
                    });
            System.out.println("客户端 ok..");
            //启动客户端去链接服务器
            //关于ChannelFuture要分析 涉及netty的异步模型
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();
            //给关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }

    }
}
